package cn.xd.learn.itstack.dbatis.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @Classname Resourcces
 * @Description resource文件转Reader的工具类
 * @Date 2022/4/25 上午11:04
 * @Created by lvxiaodong
 */
public class Resources {

    /**
     * 资源问文件转为 InputStreamReader
     * @param resource
     * @return
     * @throws IOException
     */
    public static Reader getResourceAsReader(String resource) throws IOException {
        InputStream resourceAsStream = getResourceAsStream(resource);
        return  new InputStreamReader(resourceAsStream);
    }


    /**
     * 资源文件转为 InputStream
     * @param resource
     * @return
     * @throws IOException
     */
    private static InputStream getResourceAsStream(String resource) throws IOException {
        ClassLoader[] classLoaders = getClassLoaders();
        for (ClassLoader classLoader : classLoaders) {
            InputStream inputStream = classLoader.getResourceAsStream(resource);
            if (null != inputStream) {
                return inputStream;
            }
        }
        throw new IOException("Could not find resource " + resource);
    }

    /**
     * 获取应用程序的类加载器
     * @return
     */
    private static ClassLoader[] getClassLoaders() {
        return new ClassLoader[]{
                ClassLoader.getSystemClassLoader(),
                Thread.currentThread().getContextClassLoader()};
    }

}
